package consul

import (
	"fmt"
	"github.com/hashicorp/consul/api"
	uuid "github.com/satori/go.uuid"
	"heightFive/Day_exam/day3/userRpc/global"
)

type Register struct {
	Host string
	Port int
}

type RegistryClient interface {
	RegisterConsul() error
	DeRegister(serviceId string) error
	GetService() map[string]*api.AgentService
	FilterService(serviceId string) map[string]*api.AgentService
}

func NewRegisterClient(host string, port int) RegistryClient {
	return &Register{
		Host: host,
		Port: port,
	}
}

func (r *Register) RegisterConsul() error {
	registration := &api.AgentServiceRegistration{
		ID:   uuid.NewV4().String(),
		Name: global.GlobalConfig.Consule.Name,
		Tags: global.GlobalConfig.Consule.Tag,
		Port: global.GlobalConfig.Consule.Port,
	}
	global.ConsulClient.Agent().ServiceRegister(registration)
	return nil
}

func (r *Register) DeRegister(serviceId string) error {
	err := global.ConsulClient.Agent().ServiceDeregister(serviceId)
	return err
}

func (r *Register) GetService() map[string]*api.AgentService {
	result, err := global.ConsulClient.Agent().Services()
	if err != nil {
		panic(err)
	}
	return result
}

func (r *Register) FilterService(serviceName string) map[string]*api.AgentService {
	result, err := global.ConsulClient.Agent().ServicesWithFilter(fmt.Sprintf(`Service == "%s"`, serviceName))
	if err != nil {
		panic(err)
	}
	return result
}
